package com.gyt.framework.component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gyt.framework.common.utils.HmacUtil;
import com.gyt.framework.common.utils.HttpBaseUtil;
import com.gyt.framework.exception.BaseException;
import com.gyt.framework.properties.AbtProperties;
import com.gyt.framework.response.Page;
import com.gyt.framework.response.result.AbtExperimentInfoResult;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author created by v_yantgao
 * @Date 2021/1/11 15:34
 */
@Component
public class AbtComponent {

    private final static Logger logger = LoggerFactory.getLogger(AbtComponent.class);
    @Autowired
    private AbtProperties abtProperties;

    /**查询实验列表接口**/
    private static String abt_experiment_list = "http://%1$s/rest/experiment/new_gray_exp_strategy_get_list";

    /**
     *  获取ABT实验列表
     *  @param userName 登陆用户
     * @param module 层编号
     * @param status 实验状态，0：下线；1：上线；2：审核不通过；3：审核中
     * @param curPage 当前页
     * @param pageSize 每页大小
     */
    public Page<AbtExperimentInfoResult> getAbtExperimentList(String userName, String module, String status,
                                     int curPage, int pageSize){
        Page<AbtExperimentInfoResult> page = new Page<>();
        userName = "v_yantgao";
        Map<String, String> paramMap = assembleParamMap();
        String sign = HmacUtil.signHmacSha256(paramMap, abtProperties.getToken());

        String ipPort = "100.122.186.78:80";
        String reqUrl = String.format(abt_experiment_list, ipPort);

        //封装请求参数
        Map<String, String> reqMap = new HashMap<>();
        reqMap.put("module", module);
        reqMap.put("status", status);
        reqMap.put("curPage", String.valueOf(curPage));
        reqMap.put("pageSize",String.valueOf(pageSize));
        //封装请求头
        Map<String, String> headerMap = reqHeaderMap(sign, userName, paramMap);
        long startTime = System.currentTimeMillis();
        try {
            String body = HttpBaseUtil.get(reqUrl, reqMap, headerMap);
            Map<String,Object> resultMap = JSON.parseObject(body);
            if (resultMap.get("status") != null &&
                    "success".equals(resultMap.get("status").toString())){
                logger.info("sign:{},reqMap:{},headerMap:{},resultMap:{}",
                        sign, JSON.toJSONString(reqMap),JSON.toJSONString(headerMap),JSON.toJSONString(resultMap));
                String data = resultMap.get("data") != null ? resultMap.get("data").toString() : null;
                if (StringUtils.isNotBlank(data)){
                    Map<String,Object> dataMap = JSON.parseObject(data);
                    long total = dataMap.get("total") != null ? Long.parseLong(dataMap.get("total").toString()) : 0L;
                    long pageCount = total % pageSize == 0 ? total / pageSize: (total / pageSize) + 1L;//分页数
                    if (dataMap.get("businesss") != null) {
                        List<AbtExperimentInfoResult> expInfoResults = JSON.parseArray(dataMap.get("businesss").toString(), AbtExperimentInfoResult.class);
                        page.setList(expInfoResults);
                        page.setPageNum(curPage);
                        page.setPageSize(pageSize);
                        page.setTotal(total);
                        return page;
                    }
                }
            }
            return page;
        } catch (Exception e) {
            throw new BaseException("500", "获取实验列表失败！");
        } finally {
            long endTime = System.currentTimeMillis();
            logger.info("abt_experiment_list cost time:{}",(endTime - startTime));
        }

    }

    /**
     * 请求头header
     * @param sign
     * @param userName
     * @param paramMap
     * @return
     */
    private Map<String, String> reqHeaderMap(String sign, String userName, Map<String, String> paramMap){
        Map<String, String> map = new HashMap<>();
        map.put("x-abt-businessCode",paramMap.get("businessCode"));
        map.put("x-abt-timestamp", paramMap.get("timestamp"));
        map.put("x-abt-nonce",paramMap.get("nonce"));
        map.put("x-abt-version",abtProperties.getVersion());
        map.put("x-abt-sign", sign);
        map.put("x-abt-user", userName);
        return map;
    }
    /**
     * 组装公共参数
     * @return
     */
    private Map<String,String> assembleParamMap(){
        Map<String, String> map = new HashMap<>();
        map.put("businessCode", abtProperties.getBusinessCode());
        map.put("timestamp", String.valueOf(System.currentTimeMillis()));
        map.put("nonce", RandomStringUtils.randomAlphanumeric(16));
        //map.put("token", abtProperties.getToken());
        map.put("version", abtProperties.getVersion());
        return map;
    }
}
